package com.example.login.view

import android.view.View
import androidx.activity.viewModels

import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.login.R
import com.bawei.login.databinding.ActivityLoginBinding
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.base.RouterPath
import com.example.common.base.BaseActivity
import com.example.common.mvi.BaseMviActivity
import com.example.login.entity.LoginValues
import com.example.login.intent.LoginViewIntent
import com.example.login.state.LoginUiState
import com.example.login.vm.LoginViewModel
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.launch

/**
 * 登录相关业务：
 * 常见登录：手机号+验证码，账号+密码，邮箱+密码
 * 第三方平台登录：QQ，微信，微博，抖音，淘宝等
 * 手机厂商：vivo，OPPO，小米，华为，苹果等
 * 其他方式：指纹登录，人脸识别
 */

@Route(path = RouterPath.PATH_LOGIN_PAGE)
class LoginActivity : BaseMviActivity<ActivityLoginBinding>() {
    private val mViewModel:LoginViewModel by viewModels()
    override fun getLayoutId(): Int = R.layout.activity_login
    override fun initView() {

        //获取之前保存账号和密码
        var preAccount = MMKV.defaultMMKV().decodeString("pre_account","")
        var prePwd = MMKV.defaultMMKV().decodeString("pre_pwd","")

        if(!preAccount.isNullOrEmpty()&&!prePwd.isNullOrEmpty()){
            mDataBinding.includeLogin.cbRememberPwd.isChecked = true
            mDataBinding.includeLogin.edtLoginName.setText(preAccount)
            mDataBinding.includeLogin.edtLoginPwd.setText(prePwd)
        }

        //注册账号点击事件
        mDataBinding.includeLogin.tvRegister.setOnClickListener{
            mDataBinding.cltLoginCard.visibility = View.INVISIBLE
            mDataBinding.cltRegisterCard.visibility = View.VISIBLE
            mDataBinding.llUserAgreement.visibility = View.INVISIBLE
        }

        //登录点击事件
        mDataBinding.includeLogin.btnLogin.setOnClickListener{
            var userName = mDataBinding.includeLogin.edtLoginName.text.toString().trim()
            var userPwd = mDataBinding.includeLogin.edtLoginPwd.text.toString().trim()
            if(!mDataBinding.cbAgree.isChecked){
                showToastMsg("请先同意用户协议")
            }else{
                loginToServer(userName,userPwd)
            }
        }

        mDataBinding.includeRegister.btnRegister.setOnClickListener{
            var userName = mDataBinding.includeRegister.edtRegisterName.text.toString().trim()
            var userPwd = mDataBinding.includeRegister.edtRegisterPwd.text.toString().trim()
            var userRePwd = mDataBinding.includeRegister.edtRegisteRePwd.text.toString().trim()
            if(userName.isNullOrEmpty()&&userPwd.isNullOrEmpty()&&userRePwd.isNullOrEmpty()){
                ToastUtils.showLong("账号/密码不得为空")
                return@setOnClickListener
            }
            if(userPwd.equals(userRePwd)){
                registToServer(userName,userPwd)
            }else{
                ToastUtils.showLong("两次密码输入的不一致")
                return@setOnClickListener
            }

        }

    }

    private fun registToServer(userName: String, userPwd: String) {
        lifecycleScope.launch {
            mViewModel.channel.send(LoginViewIntent.RegisterToServer(userName,userPwd))
        }
    }

    private fun loginToServer(userName: String, userPwd: String) {
        lifecycleScope.launch {
            mViewModel.channel.send(LoginViewIntent.LoginToServer(userName,userPwd))
        }
    }

    override suspend fun collectUiState() {
        mViewModel.uiState.collect {
            when (it) {
                is LoginUiState.LoginSuccess -> handLoginSuccess(it.data)
                is LoginUiState.RegisterSuccess -> handRegisterSuccess(it.data)
                is LoginUiState.LoginFail -> showToastMsg(it.msg)
                is LoginUiState.RegisterFail -> showToastMsg(it.msg)
                else -> {}
            }
        }
    }

    private fun handRegisterSuccess(data: Any) {
        var entity = data as LoginValues
        //回显到登录输入框中
        mDataBinding.includeLogin.edtLoginName.setText(entity.uName)
        mDataBinding.includeLogin.edtLoginPwd.setText(entity.uPwd)
        showToastMsg("注册成功!")

        //切换登录卡片
        mDataBinding.cltLoginCard.visibility =View.VISIBLE
        mDataBinding.cltRegisterCard.visibility = View.INVISIBLE
        mDataBinding.llUserAgreement.visibility = View.VISIBLE
    }

    private fun handLoginSuccess(data: Any) {


        var entity = data as LoginValues
        if(mDataBinding.includeLogin.cbRememberPwd.isChecked){
            MMKV.defaultMMKV().encode("pre_account",entity.uName)
            MMKV.defaultMMKV().encode("pre_pwd",entity.uPwd)
        }
        //跳转到主页
        ARouter.getInstance().build(RouterPath.PATH_MAIN_PAGE).navigation()

        this@LoginActivity.finish()

    }


}